<template>
    <PopUps :bgIndex="1000" :boxIndex="1001" widthMy='60%'  height-my="78%">
        <div class="popups-box">
            <div class="header">
                <div class="header-top">
                    <h3>{{ props.popTitle }}合同</h3>
                    <i class="iconfont icon-icon-cross-empty" @click="closePopUps"></i>
                </div>
                <div class="headerMain">
                    <el-form ref="formRef" :inline="true" :model="popUpsForm" :rules="rules" class="demo-form-inline">
                        <el-form-item :prop="item.name" :label="item.label" v-for="(item, index) in popUpsFormLabel"
                            :key="index" :style="{ 'min-width': `${item.minWidth}'!important'` }"
                            :class="item.classTypeName">
                            <!-- 输入框 -->
                            <div class="optionsInput">
                                <el-input v-model="popUpsForm[item.name]" clearable
                                    :disabled="item.disabled || props.disabled" v-if="!item.type || item.type == 'input'" />
                                <el-button v-if="item.btn && !props.disabled" class="btnPotions" @click="flag = true">{{
                                    item.btn
                                }}</el-button>
                            </div>
                            <!-- 下拉选框 -->
                            <el-select v-model="popUpsForm[item.name]" clearable :disabled="props.disabled"
                                v-if="item.type == 'select'">
                                <el-option :label="item1.label" :value="item1.value" v-for="item1 in item.client"
                                    :key="item1.value" />
                            </el-select>
                            <!-- 开始到结束 -->
                            <el-date-picker v-model="popUpsForm[item.name]" v-else-if="item.type == 'datetimerange'" :disabled="props.disabled"
                                type="datetimerange" start-placeholder="开始" end-placeholder="结束" format="YYYY-MM-DD"
                                date-format="YYYY/MM/DD" time-format="HH:mm" value-format="YYYY-MM-DD" />
                            <!-- 日期选框 -->
                            <el-date-picker v-else-if="item.type == 'picker'" :disabled="props.disabled"
                                v-model="popUpsForm[item.name]" type="date" placeholder="请输入日期" format="YYYY-MM-DD"
                                value-format="YYYY-MM-DD" />
                            <!-- 文本域 -->
                            <el-input :disabled="props.disabled" v-model="popUpsForm[item.name]" type="textarea"
                                v-else-if="item.type == 'textarea'" />
                        </el-form-item>
                  <div class="mainContent">
                    <h3>合同附件</h3>
                  </div>
                  <div class="content">
                    <el-form-item label="上传附件" prop="files" class="filesContent" :required="true">
                      <FileUpload v-model="popUpsForm.files"
                                  :fileType='["doc", "docx", "xls", "ppt", "txt", "pdf", "xlsx"]' :limit="1"
                                  :modelValue="popUpsForm.files" @update:modelValue="handlerModelValue" v-if="!props.disabled"/>
                      <p v-else>{{ popUpsForm.files }}</p>
                    </el-form-item>
                    <el-form-item label="经办人" prop="attn" :required="true">
                      <el-input v-model="popUpsForm.attn" type="text" autocomplete="off" :disabled="props.disabled"/>
                    </el-form-item>

                  </div>
                  <div class="btn">
                    <el-button type="primary" @click="onSubmit(formRef)" class="submit" v-if="props.defindFlag">
                      {{
                        props.popTitle
                      }}
                    </el-button>
                    <el-button type="primary" @click="closePopUps" class="reset">取消</el-button>
                  </div>
                    </el-form>

                </div>

            </div>
        </div>
        <PopUps widthMy='60%'  height-my="78%" v-if="flag" :bgIndex="1002" :boxIndex="1003">
            <div class="optionsOrder">
                <header>选择订单号</header>
                <el-form :inline="true" :model="optionsOrderForm" ref="optionsOrderFormRef" class="form-inline">
                    <el-form-item label="下单日期" class="startTime" prop="orderDate">
                        <el-date-picker clearable v-model="optionsOrderForm.orderDate" type="date" format="YYYY-MM-DD"
                            value-format="YYYY-MM-DD" />
                    </el-form-item>
                    <el-form-item label="单据编号" prop="orderId">
                        <el-input v-model="optionsOrderForm.orderId" />
                    </el-form-item>
                    <el-form-item label="客户名称" prop="customerId">
                        <el-select v-model="optionsOrderForm.customerId" popper-class="deptIdSelect"
                            @visible-change="selectChange($event, customerId, 'customerName')" clearable>
                            <el-input v-model="customerModel" style="width: 90%"
                                @input="InputSearchChangeHandler(customerId, 'customerName')">
                                <template #prefix>
                                    <el-icon class="el-input__icon">
                                        <search />
                                    </el-icon>
                                </template>
                            </el-input>
                            <template v-if="customerNameData">
                                <el-option :label="item.customerName" :value="item.customerId"
                                    v-for="item in customerNameData" :key="item.customerId" />
                            </template>
                            <template v-if="Array.isArray(customerNameData) && customerNameData.length === 0">
                                <el-option :label="item.customerName" :value="item.customerId" v-for="item in customerId"
                                    :key="item.customerId" />
                            </template>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="部门" prop="deptId">
                        <el-select v-model="optionsOrderForm.deptId" popper-class="deptIdSelect" clearable
                            @visible-change="selectChange($event, deptId, 'deptName')">
                            <el-input v-model="deptIdModel" @input="InputSearchChangeHandler(deptId, 'deptName')"
                                style="width: 90%;">
                                <template #prefix>
                                    <el-icon class="el-input__icon">
                                        <search />
                                    </el-icon>
                                </template>
                            </el-input>

                            <template v-if="deptIdData">
                                <el-option :label="item.deptName" :value="item.deptId" v-for="item in deptIdData"
                                    :key="item.deptId" />

                            </template>
                            <template v-if="Array.isArray(deptIdData) && deptIdData.length === 0">
                                <el-option :label="item.deptName" :value="item.deptId" v-for="item in deptId"
                                    :key="item.deptId" />
                            </template>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="制单人" prop="creator">
                        <el-input v-model="optionsOrderForm.creator" />
                    </el-form-item>
                    <el-form-item>
                        <div class="btn">
                            <el-button type="primary" @click="onQuery" class="submit">查询</el-button>
                            <el-button type="primary" @click="onReset(optionsOrderFormRef)" color="#E4E9FC"
                                class="reset">重置</el-button>
                        </div>
                    </el-form-item>
                </el-form>
                <div class="invoiceStatus">
                    <header>单据状态</header>
                    <forTableCom :color="color" :idActive="idActive" :bg="bg" @handleSelectionChange="handleSelectionChange"
                        :tableHeaderData="inventoryTableHeaderData" :pagination="false" :tableData="inventoryTableData"
                        height="270" @scrollhandler="scrollhandler" class="forTableComOrder">
                    </forTableCom>

                    <div class="btnSub">
                        <el-button type="primary" @click="onAdd" class="add">确认</el-button>
                        <el-button type="primary" @click="onCancel" class="cancel" color="#E4E9FC">取消</el-button>
                    </div>
                </div>
            </div>
        </PopUps>
    </PopUps>
</template>
<script setup>
import PopUps from '@/components/My/PopUps';
import { reactive, ref, defineEmits, defineProps } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus';
import { inputSearchHandler } from '@/hook/inputChange'
import FileUpload from "@/components/FileUpload"
import { addContracts, getContracts ,updateContracts} from "@/api/customer"
import { getWorkApi, getdepartmentseApi, getselectOrderApi } from '@/api/tickets/index'
import forTableCom from '@/components/forTableCom/index.vue'
import { sliceDate } from '@/utils/date.js'
const emit = defineEmits(['getoutboundOrderData', 'closePopUps'])
let props = defineProps(['popTitle', 'disabled', 'PopData', 'defindFlag', 'updateInfoDetail','newAddContractRow'])
let flag = ref(false)
const formRef = ref(null)

const optionsOrderFormRef = ref(null)
let color = '#000'
let idActive = 'orderId'
let bg = '#F6F8FE'
// 部门下拉数据
let deptId = ref([])
// 部门绑定的值
let deptIdModel = ref('')
// 部门搜索下拉数据
let deptIdData = ref([])

// 客户名称
let customerId = ref([])
// 客户名绑定的值
let customerModel = ref('')
// 客户搜索下拉数据
let customerNameData = ref([])
// 订单号选择
let optionOrderList = ref()
// 显示搜索到的值
let { SearchHandler } = inputSearchHandler()
// 在 Input 值改变时发送
const InputSearchChangeHandler = (searchValue, i) => {
    // hook
    // SearchHandler(v, arr, searchobj, includesName)
    switch (i) {
        case 'customerName':
            // 客户名
            customerNameData.value = SearchHandler(searchValue, customerModel, i)
            break;
        case 'deptName':
            // 部门
            deptIdData.value = SearchHandler(searchValue, deptIdModel, i)
            break;

        default:
            break;
    }
}
// 封装请求下拉菜单信息
const getDropDownData = (res) => {
    let { code, data } = res
    if (code == 200) {
        return data
    }
}

// 表单
let popUpsForm = ref({
    customerId: '',      // 客户名称
    businessType: '',           // 业务类型
    contractAmount: '',           // 合同金额
    orderId: '',                // 单据编号
    contractDate: '',           // 合同年限
    files: '',                  // 文件
    attn: '',                    // 经办人              // 文件上传发送路径
})
// 表单数据标题
let popUpsFormLabel = ref([
    {
        name: 'customerId',
        label: '客户名称',
        type: 'select',
        client: [

        ]
    },
    {
        name: 'businessType',
        label: '业务类型',
        type: 'select',
        client: [
            {
                label: '物料类',
                value: '0'
            },
            {
                label: '门头',
                value: '1'
            },
            {
                label: '装修类',
                value: '2'
            },
            {
                label: '活动类',
                value: '3'
            },
            {
                label: '其他',
                value: '4'
            },
        ]
    },
    {
        name: 'contractAmount',
        label: '合同金额',
    },
    {
        name: 'orderId',
        label: '单据编号',
        btn: '选择',
        defindFlag: true
    },
    {
        name: 'contractDate',
        label: '合同年限',
        type: 'datetimerange',
        classTypeName: 'datetimerangeClass'
    },
])
// 信息校验
const rules = reactive({
    customerId: [
        {
            required: true,
            message: '客户名称',
            trigger: 'change',
        }
    ],
    businessType: [
        {
            required: true,
            message: '业务类型',
            trigger: 'change',
        }
    ],
    contractAmount: [
        {
            required: true,
            message: '合同金额',
            trigger: 'change',
        }
    ],

    contractDate: [
        {
            required: true,
            message: '合同年限',
            trigger: 'change',
        }
    ],

    orderId: [
        {
            required: true,
            message: '单据编号',
            trigger: 'change',
        }
    ],
    attn: [
        {
            required: true,
            message: '经办人',
            trigger: 'change',
        }
    ],  files: [
        {
            required: true,
            message: '请上传文件',
            trigger: 'change',
        }
    ],
})

// 关闭
const closePopUps = () => {
    emit('closePopUps')
}


// 获取的图片
const handlerModelValue = (v) => {
    popUpsForm.files = v
}


// 新增
const onSubmit = (formRef) => {
    ElMessageBox.confirm(
        '确认' + props.popTitle + '信息？',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'success',
        }
    ).then(async () => {
        if (!formRef) return
        await formRef.validate((valid) => {
            if (valid) {
                if (popUpsForm.value.files) {
                    // 发送新增接口请求
                    // 发送新增请求
                    let parasm = popUpsForm.value
                    parasm.contractStartDate = parasm.contractDate[0]
                    parasm.contractEndDate = parasm.contractDate[1]
                    if(popUpsForm.value.contractId){
                        console.log('修改');
                        parasm.contractId = props.updateInfoDetail.contractId
                        updateContracts(parasm).then(res => {
                            if (res.code == 200) {
                                emit('getoutboundOrderData')
                                closePopUps()
                                ElMessage({
                                    type: 'success',
                                    message: res.msg,
                                })
                            }
                        })
                    }else{
                        addContracts(parasm).then(res => {
                            if (res.code == 200) {
                                emit('getoutboundOrderData')
                                closePopUps()
                                ElMessage({
                                    type: 'success',
                                    message: res.msg,
                                })
                            }
                        })
                    }
                } else {
                    ElMessage({
                        message: "请上传文件",
                        type: "error",
                        offset: 60
                    });
                }

            }
        })
    })
}


// 选择订单表单
const optionsOrderForm = ref({
    orderDate: '',       // 单据日期
    orderId: '',         // 单据编号
    customerId: '',         // 客户名称
    deptId: '',         // 部门
    creator: '',         // 制单人
})
// 选择订单号
const inventoryTableHeaderData = ref([
    {
        prop: 'orderDate',
        label: '单据日期',
    },
    {
        prop: 'orderId',
        label: '单据编号',
    },
    {
        prop: 'customerId',
        label: '客户名称',
    },
    {
        prop: 'businessType',
        label: '业务类型',
    },
    {
        prop: 'productionContent',
        label: '制作内容',
    },
    {
        prop: 'invoiceStatus',
        label: '单据状态',
    },
    {
        prop: 'paymentStatus',
        label: '结款状态',
    },
    {
        prop: 'totalOrderAmount',
        label: '订单总金额',
    },
    {
        prop: 'creator',
        label: '制单人',
    },
])
// 选择订单号的表格数据
const inventoryTableData = ref([

])

// 获取部门下拉菜单数据
const getdeptIdseApiData = async (data = '') => {
    let params = { deptName: data }
    let res = await getdepartmentseApi(params)
    deptId.value = getDropDownData(res)
}
// 第一次进入获取一级二级弹窗的客户下拉数据
const getCustomerData = (res) => {
    customerId.value = getDropDownData(res)
    let rowList = []
    res.data.forEach(v => {
        rowList.push({
            value: v.customerId,
            label: v.primaryClassification + '/' + v.customerName,
        })
    })
    popUpsFormLabel.value[0].client = rowList
}
// 获取客户下拉菜单数据
const getWorkApiData = async (data = '', contcatData = true) => {
    let params = { 'customerId': data }
    let res = await getWorkApi(params)
    if (contcatData) {
        getCustomerData(res)
    } else {
        // 关联 客户地址 客户电话 客户
        popUpsForm.value.contactPhone = res.data[0].contactPhone
        popUpsForm.value.customerContacts = res.data[0].customerContacts
        popUpsForm.value.customerAddress = res.data[0].address
    }
}
// 关闭拉下时清除搜索框的值
const selectChange = (event, v, v1) => {
    if (event == false) {
        customerModel.value = ''
        deptIdModel.value = ''
        InputSearchChangeHandler(v, v1)
    }
}
// 选择订单号查询
const onQuery = () => {
    let params = {
        orderDate: optionsOrderForm.value.orderDate,       // 单据日期
        orderId: optionsOrderForm.value.orderId,         // 单据编号
        customerId: optionsOrderForm.value.customerId,         // 客户名称
        deptId: optionsOrderForm.value.deptId,         // 部门
        creator: optionsOrderForm.value.creator,         // 制单人
    }
    getselectOrderData(params)
}
// 选择订单号重置
const onReset = (ref) => {
    if (!ref) return
    ref.resetFields()
}
// 选择的列
const handleSelectionChange = (v) => {
    optionOrderList.value = v
}
// 订单号确认
const onAdd = () => {
    if (optionOrderList.value.length == 1) {
        console.log(optionOrderList.value[0]);
        popUpsForm.value.orderId = optionOrderList.value[0].orderId
        flag.value = false
    } else {
        ElMessage({
            type: 'warning',
            message: '只能勾选一个@^@',
        })
    }
}
// 取消
const onCancel = () => {
    flag.value = false
}
let pageNum = ref(1)    // 页数
let pageSize = ref(50)  // 条数
let totals = ref(12)
// 工单详情接口
const getselectOrderData = async (params = '') => {
    let res = await getselectOrderApi(params)
    let { code, rows, total } = res
    if (code === 200) {
        sliceDate(rows, 'orderDate')
        totals.value = total
        inventoryTableData.value = []
        rows.forEach((v, i) => {
            inventoryTableData.value.push(v)
            inventoryTableData.value[i].customerId = v.customerId
            inventoryTableData.value[i].businessType = v.productionVOS[0]?.businessType
            inventoryTableData.value[i].productionContent = v.productionVOS[0]?.productionContent
        })
    }
}
// 滑动到底部
const scrollhandler = () => {
    let params = {
        pageNum: pageNum.value++,
        pageSize: pageSize.value + 12
    }
    // 数据请求对比优化
    if (totals.value > inventoryTableData.value.length) {
        getselectOrderData(params)
    }
}

// 数据回显
const assignmentFun = async () => {
    let { code, data } = await getContracts(props.updateInfoDetail.contractId)
    if (code == 200) {
        for (const key in popUpsForm.value) {
            popUpsForm.value[key] = data[key]
        }
        popUpsForm.value.contractId = data.contractId
        popUpsForm.value.customerId = String(popUpsForm.value.customerId)
        popUpsForm.value.contractDate = [data.contractStartDate,data.contractEndDate]
    }
}
onMounted(() => {
    getWorkApiData()
    getdeptIdseApiData()
    getselectOrderData()
    // 数据回显
    if (props.updateInfoDetail) {
        assignmentFun()
    }


  if(props.newAddContractRow){
    popUpsForm.value.customerId = props.newAddContractRow.customerId
    popUpsForm.value.customerName = props.newAddContractRow.customerName
    popUpsForm.value.orderId = props.newAddContractRow.orderId
  }
  console.log(popUpsForm.value)
})

</script>

<style lang="scss" scoped>
.demo-form-inline .el-select {
    --el-select-width: 220px;
}

.form-inline {
    :deep(.el-form-item__label) {
        width: 80px;
    }

    :deep(.el-form-item) {
        width: 190px;
    }
}

:deep(.datetimerangeClass) {
    width: 334px !important;
}

.el-input__wrapper {
    --el-select-width: 220px;
}



:deep(.el-form-item__label) {
    width: 120px;
    text-align: right;
}

:deep(.el-textarea__inner) {
    width: 180px;
}

.optionsInput {
    display: flex;
    align-items: center;

    .btnPotions {
        background-color: #829BFF;
        color: #fff;
        margin-left: 15px;
        width: 50px;
        height: 25px;
        display: flex;
        align-items: center;
        justify-content: center;
    }
}

@mixin publicH3 {
    font-weight: 550;
    position: relative;
    font-size: 16px !important;

    &::after {
        content: '';
        width: 5px;
        height: 20px;
        background-color: #1947FF;
        border-radius: 5px;
        position: absolute;
        left: -15px;
        top: -2px;
    }
}

@mixin titlePadding {
    padding: 25px 25px 25px 45px;
}

@mixin pubilcForm {

    :deep(.el-form-item__label) {
        font-size: 14px;
    }

    :deep(.el-input__wrapper) {
        width: 132px;
    }

    :deep(.el-date-editor--datetimerange) {
        width: 240px;
    }

    :deep(.el-table .el-table__header-wrapper th, .el-table .el-table__fixed-header-wrapper th) {
        font-size: 15px !important;
    }
}

h3 {
    @include publicH3;
}

.iconfont {
    color: #666;
    font-size: 27px;
}

.popups-box {

    .header {

        .header-top,
        .mainContent {
            @include titlePadding;
            display: flex;
            align-items: center;
            justify-content: space-between;
            position: sticky;
            top: 0px;
            background: #FFF;
        }

        .content {
            padding: 5px 25px 25px 45px;

            .filesContent {
                :deep(.el-form-item__label) {
                    height: 71px;
                    line-height: 71px;
                }
            }

            .upload-demo {
                width: 200px;

                :deep(.el-upload-dragger) {
                    padding: 0 !important;
                    height: 71px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                }

                .iconfont {
                    color: #999;
                }
            }

            :deep(.el-upload__tip) {
                width: 320px;
                color: #999;
            }
        }

        .headerMain {
            .demo-form-inline {
                @include pubilcForm;
            }


        }
    }

    .btn {
        padding-right: 50px;
        text-align: right;

        .el-button {
            width: 50px;
            height: 25px;
            font-size: 12px;
        }

        .reset {
            background-color: #E4E9FC;
            color: #333;
            border: none;
        }
    }
}

.forTableComOrder {
    padding: 0;
}

.optionsOrder {
    padding: 20px 20px 0 20px;
    height: 100%;

    header {
        margin-bottom: 20px;
        font-weight: 550;
    }



    .btnSub {
        width: 100%;
        text-align: right;
        margin-top: 30px;

        .el-button {
            width: 50px;
            height: 25px;
            font-size: 12px;
        }
    }
}
</style>